<?php

namespace mpend\models\searchs;

use Yii;
use common\helpers\ArrayHelper;

/**
 * 需求分类栏目检索
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DemandSearch extends \common\models\demand\Demand {

    public $keyword;
    public $cid;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return ArrayHelper::merge(parent::rules(), [
            [['keyword', 'cid'], 'safe'],
        ]);
    }

    public function getMedias() {
        if ($this->thumb) {
            return [
                [
                    'path' => $this->thumbUrl,
                    'format' => 'image',
                ]
            ];
        }
        return $this->images;
    }

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->active(static::STATUS_ACTIVE);
        if ($this->cid) {
            $query->andFilterWhere([
                $alias . 'category_id' => $this->cid
            ]);
        }
        if ($this->keyword) {
            $query->andFilterWhere([
                'or',
                ['like', $alias . 'title', $this->keyword],
                ['like', $alias . 'description', $this->keyword],
            ]);
        }
        $query->orderBy([
            $alias . 'created_at' => SORT_DESC,
        ]);
        return $query;
    }

    public function getExtend() {
        $data = [];
        $data[] = $this->publishTime;
        $data[] = $this->user ? $this->user->userName : '科技特派员';
//        $category = $this->category;
//        if ($category) {
//            $data[] = $category->name;
//        }
//        $data[] = $this->publishTime;
        return implode(' ', $data);
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id',
            'title',
            'description',
            'extend',
            'medias',
            'format',
            'mplink',
        ];
    }

}
